﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;


namespace MO.ModelingClient
{
    public partial class TableControl : UserControl
    {
        DataConfig config;
        bool isAdd = false;
        public bool IsAdd { get { return isAdd; } }
        public Action<Dictionary<string, object>> AfterInsert;
        public Action<string> AfterDelete;
        public TableControl()
        {
            InitializeComponent();
        }
        public void Init(DataConfig config)
        {
            config.TableControl = this;
            this.config = config;
            panel.Controls.Clear();
            RefreshTree();
        }
        public string GetKey()
        {
            if (isAdd)
                return null;
            return ((DataRow)treeView.SelectedNode.Tag)[config.KeyField] as string;
        }
        public int GetCount()
        {
            return treeView.Nodes.Count;
        }
        void RefreshTree()
        {
            treeView.Nodes.Clear();
            List<string> whereList = new List<string>();
            foreach (var item in config.KeyDict)
            {
                if (item.Value is string)
                    whereList.Add(item.Key + " = '" + item.Value + "'");
                else
                    whereList.Add(item.Key + " = " + item.Value);
            }
            string sqlStr = "select * from " + config.TableName;
            if (config.KeyDict.Count > 0)
                sqlStr += " where " + string.Join(" and ", whereList.ToArray());
            if (!string.IsNullOrEmpty(config.OrderField))
            {
                sqlStr += " order by " + config.OrderField;
            }
            DataTable table = DbOperation.DB.ExecuteDataTable(sqlStr);
            foreach (DataRow row in table.Rows)
            {
                TreeNode node = new TreeNode();
                node.Text = row[config.TitleField].ToString();
                node.Tag = row;
                treeView.Nodes.Add(node);
            }
        }
        void GenerateControls()
        {
            panel.Controls.Clear();
            foreach (ItemData item in config.FieldList)
            {
                //Control control = null;
                //if (item.Type == DataType.String)
                //    control = new ItemTextControl(item.Name, item.Default as string);
                //else if (item.Type == DataType.Number)
                //    control = new ItemNumberControl(item.Name);
                //else if (item.Type == DataType.Time)
                //    control = new ItemTimeControl(item.Name);
                //else if (item.Type == DataType.Bool)
                //    control = new ItemCheckboxControl(item.Name, item.Description);
                //else if (item.Type == DataType.Enum)
                //    control = new ItemEnumControl(item.Name, item.Enums);
                //else if (item.Type == DataType.Field)
                //    control = new ItemFieldControl(item.Name);
                //else if (item.Type == DataType.ChildTable)
                //    control = new ItemChildTableControl(item.Name, item.ChildConfig, config.KeyField, GetKey());
                //control.Tag = item;
                //AddControl(control);
                AddControl(item.CreateControl());
            }
        }
        void AddControl(Control control)
        {
            control.Width = panel.Width - 50;
            if (panel.Controls.Count > 0)
                control.Location = new Point(1, panel.Controls[panel.Controls.Count - 1].Location.Y + control.Height + 1);
            else
                control.Location = new Point(1, 1);
            panel.Controls.Add(control);
        }


        private void treeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            DataRow row = (DataRow)e.Node.Tag;
            GenerateControls();
            foreach (ItemBaseControl control in panel.Controls)
            {
                ItemData item = (ItemData)control.Tag;
                if (!item.IsDd)
                    continue;
                control.SetValue(row[item.Code]);
                if (item.Code == config.KeyField)
                    control.SetEnabled(false);
            }
        }
        private void AddMenuItem_Click(object sender, EventArgs e)
        {
            //Dictionary<string, object> dict = new Dictionary<string, object>();
            //dict["ED_Code"] = "sdfs";
            //dict["ED_Name"] = "fgjhfdj";
            //dict["ED_Description"] = "sadf";
            //dict["ED_Parent"] = null;
            //DbOperation.DB.Insert(config.TableName, dict);
            isAdd = true;
            GenerateControls();
        }
        private void SaveMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (isAdd)
                {
                    Dictionary<string, object> dict = new Dictionary<string, object>();
                    foreach (ItemBaseControl control in panel.Controls)
                    {
                        ItemData item = (ItemData)control.Tag;
                        if (!item.IsDd)
                            continue;
                        dict[item.Code] = control.GetValue();
                    }
                    foreach (var item in config.KeyDict)
                    {
                        dict.Add(item.Key, item.Value);
                    }
                    DbOperation.DB.Insert(config.TableName, dict);
                    if (AfterInsert != null)
                        AfterInsert(dict);
                    panel.Controls.Clear();
                    isAdd = false;
                    AddControl(new Label() { Text = "添加成功" });
                    RefreshTree();
                }
                else
                {
                    Dictionary<string, object> dict = new Dictionary<string, object>();
                    object key = null;
                    foreach (ItemBaseControl control in panel.Controls)
                    {
                        ItemData item = (ItemData)control.Tag;
                        if (!item.IsDd)
                            continue;
                        if (item.Code == config.KeyField)
                            key = control.GetValue();
                        else
                            dict[item.Code] = control.GetValue();
                    }
                    dict.Add("\r", null);
                    dict.Add(config.KeyField, key);
                    foreach (var item in config.KeyDict)
                    {
                        dict.Add(item.Key, item.Value);
                    }
                    DbOperation.DB.Update(config.TableName, dict);
                    panel.Controls.Clear();
                    AddControl(new Label() { Text = "修改成功" });
                    RefreshTree();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this.FindForm(), ex.Message, "");
            }
        }

        private void DeleteMenuItem_Click(object sender, EventArgs e)
        {
            if (this.treeView.SelectedNode == null)
                return;
            if (MessageBox.Show(this.FindForm(), "您确定删除：" + this.treeView.SelectedNode.Text, "删除", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                DataRow row = (DataRow)this.treeView.SelectedNode.Tag;
                string whereStr = "";
                foreach (var item in config.KeyDict)
                {
                    if (item.Value is string)
                        whereStr += " and " + item.Key + " = '" + item.Value + "'";
                    else
                        whereStr += " and " + item.Key + " = " + item.Value;
                }
                DbOperation.DB.ExecuteQuery("delete from " + config.TableName + " where " + config.KeyField + " = {0} " + whereStr, row[config.KeyField].ToString());
                if (AfterDelete != null)
                    AfterDelete(row[config.KeyField].ToString());
                panel.Controls.Clear();
                AddControl(new Label() { Text = "删除成功" });
                RefreshTree();
            }
        }
    }
}
